/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.service.*;
import com.jeeplus.modules.fee.util.Exportprofit;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 应收结算单Controller
 * @author 李超辉
 * @version 2018-06-07
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/js")
public class JsController extends BaseController {

	@Autowired
	private JsService jsService;
	@Autowired
	private JsDetilService jsDetilService;
	@Autowired
	private RecivedDetilService recivedDetilService;
	@Autowired
	private ReceivableService receivableService;
	@Autowired
	private NewReService newReService;
	
	@ModelAttribute
	public Js get(@RequestParam(required=false) String id) {
		Js entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = jsService.get(id);
		}
		if (entity == null){
			entity = new Js();
		}
		return entity;
	}
	
	/**
	 * 应收结算单列表页面
	 */
	@RequiresPermissions("fee:js:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/jsList";
	}

	/**
	 * 应收结算单报表页面
	 */
	@RequiresPermissions("fee:js:list")
	@RequestMapping(value = "list1")
	public String list1() {
		return "modules/fee/2/jsList";
	}
	/**
	 * 应收结算单报表页面
	 */
	@RequiresPermissions("fee:js:list")
	@RequestMapping(value = "list2")
	public String list2() {
		return "modules/fee/3/jsList";
	}
	
		/**
	 * 应收结算单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:js:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Js js, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			js.setPro(pro);
		}
		Page<Js> page = jsService.findPage(new Page<Js>(request, response), js);
		return getBootstrapData(page);
	}

	/**
	 * 结算单报表
	 */
	@RequestMapping(value="cx")
	@ResponseBody
	public String cx(String min,String max,String pro,String fph,String s){
		Js j=new Js();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			j.setPro(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				j.setPro(UserUtils.getUseroffice());
			}
		}
        j.setMax(max);
		j.setMin(min);
		j.setFph(fph);
		j.setStatus(s);
		List<Js> list=jsService.findList(j);
		double kp=0.0;
		double hx=0.0;
		double whx=0.0;
		String ids="";
		for(Js js:list){
            kp+=Double.parseDouble(js.getKpje());
			hx+=Double.parseDouble(js.getHxje());
			whx+=Double.parseDouble(js.getWhxje());
			ids+=js.getId()+",";
		}
		NumberFormat nf = NumberFormat.getInstance();
		j.setKpje(nf.format(kp).replaceAll(",",""));
		j.setHxje(nf.format(hx).replaceAll(",",""));
		j.setWhxje(nf.format(whx).replaceAll(",",""));
		j.setMax(ids);
		list.add(j);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<Js> list =new ArrayList<Js>();
		for(String id:idd){
			list.add(jsService.get(id));
		}

		Exportprofit e=new Exportprofit();
		e.exportjs(response,list);
	}
	/**
	 * 查看，增加，编辑应收结算单表单页面
	 */
	@RequiresPermissions(value={"fee:js:view","fee:js:add","fee:js:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Js js, Model model) {
		JsDetil jsDetil=new JsDetil();
		jsDetil.setJs(js.getId());
		List<JsDetil> list=jsDetilService.findList(jsDetil);
		model.addAttribute("list", list);
		RecivedDetil recivedDetil=new RecivedDetil();
		recivedDetil.setRecive(js.getId());
		List<RecivedDetil> l=recivedDetilService.findList(recivedDetil);
		model.addAttribute("js", js);
		model.addAttribute("l", l);
		return "modules/fee/jsForm";
	}


	/**
	 * 开票
	 */
	@RequiresPermissions(value={"fee:js:view","fee:js:add","fee:js:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(Js js, Model model,String sy,String w,String i) {
		NumberFormat nf = NumberFormat.getInstance();
		js.setKpje(nf.format(Double.parseDouble(sy)).replaceAll(",",""));
		js.setSl(nf.format(Double.parseDouble(w)).replaceAll(",",""));
		double dj=Double.parseDouble(sy)/Double.parseDouble(w);
		js.setDj(nf.format(dj).replaceAll(",",""));
		model.addAttribute("js", js);
		model.addAttribute("ids", i);
		return "modules/fee/1/jsForm";
	}

	/**
	 * 开票（新）
	 */
	@RequestMapping(value = "form2")
	public String form2(Js js, Model model,String sy,String w,String i) {
		NumberFormat nf = NumberFormat.getInstance();
		js.setKpje(nf.format(Double.parseDouble(sy)).replaceAll(",",""));
		js.setSl(nf.format(Double.parseDouble(w)).replaceAll(",",""));
		double dj=Double.parseDouble(sy)/Double.parseDouble(w);
		js.setDj(nf.format(dj).replaceAll(",",""));
		model.addAttribute("js", js);
		model.addAttribute("ids", i);
		return "modules/fee/3/jsForm";
	}
	/**
	 *
	 * 保存应收结算单
	 */
	@ResponseBody
	@RequiresPermissions(value={"fee:js:add","fee:js:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Js js,String ids, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, js)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		js.setWhxje(js.getKpje());
		js.setPro(UserUtils.getUseroffice());
		js.setStatus("未核销");
		js.setHxje("0");
		jsService.save(js);//新建或者编辑保存
		if(ids!=null){
		String[] i=ids.split(",");
		for(String id:i){
			Receivable receivable=receivableService.get(id);
			JsDetil jsDetil=new JsDetil();
			jsDetil.setJs(js.getId());
			jsDetil.setJsje(receivable.getFreight());
			jsDetil.setZydh(receivable.getShipmentNumbers());
			jsDetil.setThdh(receivable.getThdh());
			jsDetil.setPro(UserUtils.getUseroffice());
			jsDetil.setPid(id);
			jsDetilService.save(jsDetil);
			receivable.setReceived("1");
			receivableService.save(receivable);
		}}


		j.setSuccess(true);
		j.setMsg("保存应收结算单成功");
		return j;
	}

	/**
	 *
	 * 保存应收结算单
	 */
	@ResponseBody
	@RequestMapping(value = "save3")
	public AjaxJson save3(Js js,String ids, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, js)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		js.setWhxje(js.getKpje());
		js.setPro(UserUtils.getUseroffice());
		js.setStatus("未核销");
		js.setHxje("0");
		jsService.save(js);//新建或者编辑保存
		if(ids!=null){
			String[] i=ids.split(",");
			for(String id:i){
				NewRe receivable=newReService.get(id);
				JsDetil jsDetil=new JsDetil();
				jsDetil.setJs(js.getId());
				jsDetil.setJsje(receivable.getFreight());
				jsDetil.setZydh(receivable.getShipmentNumbers());
				jsDetil.setThdh(receivable.getThdh());
				jsDetil.setPro(receivable.getProject());
				jsDetil.setPid(id);
				jsDetilService.save(jsDetil);
				receivable.setReceived("1");
				receivable.setFph(js.getFph());
				receivable.setKprq(js.getDate());
				receivable.setKpje(receivable.getFreight());
				receivable.setDzje("0");
				receivable.setQr(js.getSpf());
				newReService.save(receivable);
			}}


		j.setSuccess(true);
		j.setMsg("保存应收结算单成功");
		return j;
	}
	
	/**
	 * 取消开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:js:del")
	@RequestMapping(value = "qxkp")
	public AjaxJson delete(Js js, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		List<JsDetil> l=jsDetilService.findList(new JsDetil(js));
		for(JsDetil jsDetil:l){
			String pid=jsDetil.getPid();
			Receivable r=receivableService.get(pid);
			r.setReceived("0");
			receivableService.save(r);
			jsDetilService.delete(jsDetil);
		}
		jsService.delete(js);
		j.setMsg("取消开票成功");
		return j;
	}

	/**
	 * 取消开票
	 */
	@ResponseBody
	@RequiresPermissions("fee:js:del")
	@RequestMapping(value = "qxkp1")
	public AjaxJson delete1(Js js, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		List<JsDetil> l=jsDetilService.findList(new JsDetil(js));
		for(JsDetil jsDetil:l){
			String pid=jsDetil.getPid();
			NewRe r=newReService.get(pid);
			r.setReceived("0");
			newReService.save(r);
			jsDetilService.delete(jsDetil);
		}
		jsService.delete(js);
		j.setMsg("取消开票成功");
		return j;
	}
	/**
	 * 关账
	 */
	@ResponseBody
	@RequiresPermissions("fee:js:del")
	@RequestMapping(value = "gz")
	public AjaxJson gz(Js js, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		js.setStatus("已关账");
		jsService.save(js);
		j.setMsg("关账成功");
		return j;
	}

	/**
	 * 获取核销明细
	 */
	@ResponseBody
	@RequestMapping(value = "getdetil")
	public String getdetil(String i, RedirectAttributes redirectAttributes) {
		RecivedDetil recivedDetil=new RecivedDetil();
		recivedDetil.setRecive(i);
		List<RecivedDetil> l=recivedDetilService.findList(recivedDetil);
		Gson g=new Gson();
		return g.toJson(l).toString();
	}

	/**
	 * 取消核销
	 */
	@ResponseBody
	@RequestMapping(value = "qdqx")
	public String qdqx(String idd, RedirectAttributes redirectAttributes) {
		String[] ids=idd.split(",");
		for(String i:ids){
		RecivedDetil recivedDetil=recivedDetilService.get(i);
		NumberFormat nf = NumberFormat.getInstance();
		Js js=jsService.get(recivedDetil.getRecive());
		Double d=recivedDetil.getMoney();
		Double e=Double.parseDouble(js.getHxje().replace(",",""));
		Double f=Double.parseDouble(js.getWhxje().replace(",",""));
		js.setHxje(nf.format(e-d).replaceAll(",",""));
		js.setWhxje(nf.format(f+d).replaceAll(",",""));
		if(js.getWhxje().equals("0.0")||js.getWhxje().equals("0")){
			js.setStatus("已核销");
		}else if(js.getHxje().equals("0")||js.getHxje().equals("0.0")){
			js.setStatus("未核销");
		}else{

			js.setStatus("部分核销");
		}
         jsService.save(js);
		recivedDetilService.delete(recivedDetil);}
		return "";
	}
	
	/**
	 * 批量删除应收结算单
	 */
	@ResponseBody
	@RequiresPermissions("fee:js:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			jsService.delete(jsService.get(id));
		}
		j.setMsg("删除应收结算单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:js:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Js js, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应收结算单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Js> page = jsService.findPage(new Page<Js>(request, response, -1), js);
    		new ExportExcel("应收结算单", Js.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应收结算单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:js:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Js> list = ei.getDataList(Js.class);
			for (Js js : list){
				try{
					jsService.save(js);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应收结算单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应收结算单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应收结算单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/js/?repage";
    }
	
	/**
	 * 下载导入应收结算单数据模板
	 */
	@RequiresPermissions("fee:js:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应收结算单数据导入模板.xlsx";
    		List<Js> list = Lists.newArrayList(); 
    		new ExportExcel("应收结算单数据", Js.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/js/?repage";
    }

}